from django.shortcuts import render, redirect
from member.models import MerchantUser, ShopperUser, ProfileImage, ACCEPTED_LOCALE
from django.conf import settings
from member.models import Request, STATUS
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
import django.utils.translation
import django.views

def index(request):
    users = MerchantUser.objects.all()
    user_out = []
    for user in users:
        if user.getActiveProfile():
            try:
                image_filter = ProfileImage.objects.get(pk=user.profile_image)
                user_out.append ((user, image_filter.thumbnail))
            except Exception:
                user_out.append ((user, "documents/unknown/unknown.jpg"))
    user_paginator = Paginator(user_out, settings.ITEMS_PER_PAGE)
    page = request.GET.get('page')
    try:
        contacts = user_paginator.page(page)
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        contacts = user_paginator.page(1)
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
        contacts = user_paginator.page(user_paginator.num_pages)
    if request.user.is_authenticated():
        user = request.user
        if user.is_superuser:
            return redirect('/admins/console/')
        #username = user.username
        try:
            user = ShopperUser.objects.get(user=user)
        except ShopperUser.DoesNotExist:
            user = MerchantUser.objects.get(user=user)
        response = render(request, 'main/index.html', {'user': user, 'users_paginator': contacts, "min_pts_amount":settings.MINIMUM_PURCHASE_AMOUNT,})
        return response
    response = render(request, 'main/index.html', {'users_paginator': contacts, "min_pts_amount":settings.MINIMUM_PURCHASE_AMOUNT,})
    return response

def display_profile(request, user_id):
    loggedUser = None
    if request.user.is_authenticated():
        try:
            loggedUser = ShopperUser.objects.get(id=request.user.id)
        except ShopperUser.DoesNotExist:
            pass
    merchantUser = MerchantUser.objects.get(id=user_id)
    enableSend = not isUserHasPendingRequests(loggedUser, merchantUser)
    language = django.utils.translation.get_language()
    profile = merchantUser.getActiveProfile().getLocProfile(ACCEPTED_LOCALE.get_constant(language.upper()), force=True)
    return render(request, 'main/profileMerchantDisplay.html', {'profile': merchantUser.getActiveProfile(),'enableSend': enableSend, "logged_user":loggedUser, "profile_text": profile.loc_profile})

def isUserHasPendingRequests(sender, recv):
    requests = Request.objects.filter(sender=sender, receiver=recv, status__in=[STATUS.DELIVERY_PENDING, STATUS.ON_REVIEW, STATUS.PENDING_ANSWER])
    if requests:
        return True
    else:
        return False
